/*
 * @Author: hfWang
 * @Date: 2022-07-18 21:28:52
 * @LastEditTime: 2022-07-20 23:24:54
 * @Description: file content
 * @FilePath: \hf-blog-2\docs\.vitepress\customConfig\getFileName.ts
 */
import * as fs from "fs";
import type { DefaultTheme } from "vitepress";

interface IOptions {
	targetPath: string;
	dirPath: string;
	targetFileName: string;
	needFilterFile: string;
}

const cwd = process.cwd();

// 获取文件名
const getFileName = (
	dirPath: string, 
	targetFileName: string = "", 
	needFilterFile: string = ""
) => {
	const targetPath = `${cwd}/docs/${dirPath}`;
	const options = {
		targetPath,
		dirPath,
		targetFileName,
		needFilterFile,
	};
	return createSidebar(options);
};

// 创建侧边导航栏
const createSidebar = (
	options: IOptions
): DefaultTheme.SidebarItem[] => {
	const { 
		targetPath, 
		targetFileName, 
		dirPath, 
		needFilterFile 
	} = options;

	let docsNameList: DefaultTheme.SidebarItem[] = [];
	const files = fs.readdirSync(targetPath, { encoding: "utf8" });

	let _files: string[] = [];
	if (targetFileName) {
		_files = files.filter((file) => file.includes(targetFileName));
	} else {
		_files = files.filter((file) => file !== "index.md");
	}
	if (needFilterFile) {
		_files = _files.filter((file) => !file.includes(needFilterFile));
	}

	_files.map((file) => {
		const fileName = file.replace(".md", "");
		const fileLink = `/${dirPath}/${fileName}`;
		docsNameList.push({
			text: fileName,
			link: fileLink,
		});
	});
	return docsNameList;
};

export default getFileName;
